package com.example.lizh.mvp_example.rxBus;

import com.jakewharton.rxrelay2.PublishRelay;
import com.jakewharton.rxrelay2.Relay;

import io.reactivex.Observable;

/**
 * 有异常处理的 RxBus
 *
 * 作用:替代 BroadcastReceiver 或 Handler 或接口或 EventBus 实现的组件通信
 *
 * 为什么需要异常处理?
 * 在订阅者处理事件出现异常后,订阅者无法再收到事件,这是 RxJava 当初本身的设计原则.
 * 但是在事件总线中这反而是个问题,不过 JakeWharton 写了即使出现异常也不会终止订阅关系 RxRelay,
 * 所以基于 RxRelay 就能写出有异常处理能力的 RxBus.
 *
 * Created by LiZhiHui on 2017/07/27
 */
public class RxBus {
    private static volatile RxBus sInstance;
    private final Relay<Object> mBus;

    private RxBus() {
        this.mBus = PublishRelay.create().toSerialized();
    }

    public static RxBus getInstance() {
        if (sInstance == null) {
            synchronized (RxBus.class) {
                if (sInstance == null) {
                    sInstance = Holder.BUS;
                }
            }
        }
        return sInstance;
    }

    public void send(Object obj) {
        mBus.accept(obj);
    }

    public <T> Observable<T> toObservable(Class<T> tClass) {
        return  mBus.ofType(tClass);
    }

    public Observable<Object> toObservable() {
        return mBus;
    }

    public boolean hasObservers() {
        return mBus.hasObservers();
    }

    private static class Holder {
        private static final RxBus BUS = new RxBus();
    }
}